import axios from 'axios'

const client = axios.create({
  //baseURL: 'http://localhost:3001/api/',
  baseURL: 'https://api.ncuos.com/api/',
  timeout: 5000,
});

client.interceptors.response.use(resp => {
  return resp
}, err => {
  if(err.response) {
    err.msg = err.response.data
  } else {
    err.msg = err.message
  }
  throw err
})

const login = (username, password) => {
  return client.post('/user/token', {
     username, password 
    }).then(({data}) => {
      if(data.status !== 1) {
        throw { msg: data.message }
      }
      return data.token
    })
}

const exam = (token) => {
  return client.get('/info/cet/zkzh', {
    headers: {
      'Authorization': 'passport ' + token,
    },
  }).then(({data}) => {
    if(data.name) {
      return data
    } else {
      throw { msg: data.msg }
    }
  })
}

let resultCookies = {}

const neeacet = (token, number) => {
  return client.get('/info/neeacet?cet_num=' + number, {
    headers: {
      'Authorization': 'passport ' + token,
    },
  }).then(({data}) => {
    if(data.status != 1) {
      throw { msg: data.msg }
    }
    resultCookies = data.result_cookies
    return data
  })
}

const neeacetSubmit = (token, number, key) => {
  return client.post('/info/neeacet', { 
    key,
    cet_num: number,
    result_cookies: resultCookies 
  }, {
    headers: {
      'Authorization': 'passport ' + token,
    },
  }).then(({data}) => {
    if(data.status != 1) {
      throw { msg: data.msg }
    }
    return data.data
  })
}

export default { login, exam, neeacet, neeacetSubmit };